using System;
using System.Windows.Controls;

namespace JustinAngel.MindwaveSensor.WP8.Controls
{
    /// <summary>
    /// Baseclass for all Mindwave controls that send VisualState updates based on Mindwave State changes and readings. 
    /// </summary>
    public abstract class MindwaveControl : Control
    {
        public MindwaveControl()
        {
            this.LayoutUpdated += MindwaveConnectionIndicator_LayoutUpdated;
        }

        void MindwaveConnectionIndicator_LayoutUpdated(object sender, EventArgs e)
        {
            this.LayoutUpdated -= MindwaveConnectionIndicator_LayoutUpdated;
            UpdateVisualState();
        }

        private IMindwaveSensor _mindwaveSensor = null;
        protected IMindwaveSensor MindwaveSensor
        {
            get
            {
                if (_mindwaveSensor == null)
                    MindwaveSensor = Mindwave.Current;
                return _mindwaveSensor;
            }
            set
            {
                if (_mindwaveSensor != null)
                {
                    _mindwaveSensor.StateChanged -= MindwaveSensorStateChanged;
                    _mindwaveSensor.CurrentValueChanged -= MindwaveSensorCurrentValueChanged;
                }
                _mindwaveSensor = value;
                _mindwaveSensor.StateChanged += MindwaveSensorStateChanged;
                _mindwaveSensor.CurrentValueChanged += MindwaveSensorCurrentValueChanged;
            }
        }

        protected virtual void MindwaveSensorCurrentValueChanged(object sender, MindwaveReadingEventArgs e)
        {
            UpdateVisualState();
        }

        /// <summary>
        /// Used to override using a specific MindwaveSensor and not the Mindwave.Current sensor.
        /// </summary>
        public void SetMindwaveSensor(IMindwaveSensor mindwaveSensor)
        {
            MindwaveSensor = mindwaveSensor;
        }

        protected virtual void MindwaveSensorStateChanged(object sender, MindwaveStateChangedEventArgs e)
        {
            UpdateVisualState();
        }

        protected virtual void UpdateVisualState()
        {
        }
    }
}